package com.android.volley.images;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;

public class ImageDataRequest extends Request<byte[]>{
    private static final int IMAGE_TIMEOUT_MS = 2000;
    /** Retry request times */
    private static final int IMAGE_MAX_RETRIES = 2;
    /** 超时时间的乘数，重试时才用到 */
    private static final float IMAGE_BACKOFF_MULT = 2f;
    private final Response.Listener<byte[]> mListener;

    /**
     * Creates a new image request
     *
     * @param url URL of the image
     * @param listener Listener to receive
     * @param errorListener Error listener, or null to ignore errors
     */
    public ImageDataRequest(String url, Response.Listener<byte[]> listener,
                             Response.ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        setRetryPolicy(new DefaultRetryPolicy(IMAGE_TIMEOUT_MS, IMAGE_MAX_RETRIES,
                IMAGE_BACKOFF_MULT));
        mListener = listener;
    }

    @Override
    public Priority getPriority() {
        return Priority.LOW;
    }

    @Override
    protected Response<byte[]> parseNetworkResponse(NetworkResponse response) {
        return Response.success(response.data, HttpHeaderParser.parseCacheHeaders(response));
    }

    @Override
    protected void deliverResponse(byte[] response) {
        mListener.onResponse(response);
    }
}
